﻿#include "LoginDlg.h"
#include <QDir>
#include <windows.h>

extern MainWindow* g_pMainwindow;
extern CLoginDlg*  g_pLoginDlg;

CLoginDlg::CLoginDlg(QWidget *parent)
	: QDialog(parent)
{
	//setupUi(this); //connect(userLogin)

	setFixedSize(640, 450);
	setMinimumSize(QSize(640, 450));
	setMaximumSize(QSize(640, 450));
	QIcon icon;
	icon.addFile(QStringLiteral(":/iconImagePng"), QSize(), QIcon::Normal, QIcon::Off);
	setWindowIcon(icon);
	loginGroup = new QGroupBox(this);
	loginGroup->setObjectName(QStringLiteral("loginGroup"));
	loginGroup->setGeometry(QRect(240, 80, 351, 291));
	QFont font;
	font.setPointSize(10);
	font.setStyleStrategy(QFont::PreferAntialias);
	loginGroup->setFont(font);
	loginGroup->setAutoFillBackground(true);
	labelServerSel = new QLabel(loginGroup);
	labelServerSel->setObjectName(QStringLiteral("labelServerSel"));
	labelServerSel->setGeometry(QRect(70, 120, 71, 16));
	labelUser = new QLabel(loginGroup);
	labelUser->setObjectName(QStringLiteral("labelUser"));
	labelUser->setGeometry(QRect(70, 40, 54, 12));
	labelPassword = new QLabel(loginGroup);
	labelPassword->setObjectName(QStringLiteral("labelPassword"));
	labelPassword->setGeometry(QRect(70, 80, 54, 12));
	editPassword = new QLineEdit(loginGroup);
	editPassword->setObjectName(QStringLiteral("editPassword"));
	editPassword->setGeometry(QRect(180, 80, 151, 20));
	editPassword->setEchoMode(QLineEdit::Password);
	checkSaveFlag = new QCheckBox(loginGroup);
	checkSaveFlag->setObjectName(QStringLiteral("checkSaveFlag"));
    checkSaveFlag->setGeometry(QRect(270, 200, 81, 16));
	btnLogin = new QPushButton(loginGroup);
	btnLogin->setObjectName(QStringLiteral("btnLogin"));
	btnLogin->setGeometry(QRect(50, 240, 75, 23));
	btnCancel = new QPushButton(loginGroup);
	btnCancel->setObjectName(QStringLiteral("btnCancel"));
	btnCancel->setGeometry(QRect(200, 240, 75, 23));
	cmbServerList = new QComboBox(loginGroup);
	cmbServerList->setObjectName(QStringLiteral("cmbServerList"));
	cmbServerList->setGeometry(QRect(180, 120, 151, 22));
	editBrokerId = new QLineEdit(loginGroup);
	editBrokerId->setObjectName(QStringLiteral("editBrokerId"));
	editBrokerId->setGeometry(QRect(180, 160, 151, 20));
	editBrokerId->setEchoMode(QLineEdit::Password);
	labelBrokerId = new QLabel(loginGroup);
	labelBrokerId->setObjectName(QStringLiteral("labelBrokerId"));
    labelBrokerId->setGeometry(QRect(70, 160, 54, 12));
    cmbUsername = new QComboBox(loginGroup);
	cmbUsername->setObjectName(QStringLiteral("cmbUsername"));
    cmbUsername->setGeometry(QRect(180, 40, 151, 22));
    labelStatus = new QLabel(loginGroup);
    labelStatus->setGeometry(QRect(70, 200, 170, 22));//状态显示Label

	//自定义账号输入框
	listWidget = new QListWidget();
	cmbUsername->setModel(listWidget->model());
	cmbUsername->setView(listWidget);
	cmbUsername->setEditable(true);

    ReadIniFile();//读取配置文件内容

    setWindowTitle(QStringLiteral("登录"));
    loginGroup->setTitle(QStringLiteral("登录信息"));
    labelServerSel->setText(QStringLiteral("服务器选择"));
    labelUser->setText(QStringLiteral("资金账号"));
    labelPassword->setText(QStringLiteral("交易密码"));
	editPassword->setInputMask(QString());
    checkSaveFlag->setText(QStringLiteral("记住密码"));
    btnLogin->setText(QStringLiteral("登录"));
    btnCancel->setText(QStringLiteral("取消"));
    editBrokerId->setInputMask(QString());
    labelBrokerId->setText(QStringLiteral("动态密码"));

	//设置背景图片
	QPixmap png = QPixmap();
	png.load(":/loginBkGrd");
	QPalette palette1 = QPalette();
	palette1.setBrush(QPalette::Background, QBrush(png));
	this->setPalette(palette1);
	this->setAutoFillBackground(true);

	int nSaveFlag = 0;
	QString szUsername(""),szPassword("");
// 	CParamSettings ps;
// 	nSaveFlag = ps.getSaveFlag();
// 	if(nSaveFlag == USF_YES)
// 	{
// 		checkSaveFlag->setChecked(true);
// 		szUsername = ps.getUserName();
// 		szPassword = ps.getPassword();
// 		editUsername->setText(szUsername);
// 		editPassword->setText(szPassword);
// 	}
	connect(btnLogin, &QPushButton::clicked,this, &CLoginDlg::userLogin);
	connect(btnCancel, &QPushButton::clicked,this, &CLoginDlg::cancelLogin);
    connect(this,SIGNAL(SigShowStatusText(QString)),this,SLOT(ShowStatusText(QString)));
	//账户输入框 输入事件绑定
	connect(cmbUsername,SIGNAL(currentTextChanged(const QString &)),this,SLOT(UserNameChanged(const QString &)));

    m_szUsername = "";
    m_szPassword = "";
}

CLoginDlg::~CLoginDlg()
{
	//删除配置文件的指针
	delete m_ServerSettings;
	delete m_AccountSettings;
	m_ServerSettings = NULL;
	m_AccountSettings = NULL;
}

void CLoginDlg::ShowStatusText(QString text){
    labelStatus->setText(text);
}

//账户输入框 输入账户名称时的响应事件
void CLoginDlg::UserNameChanged(const QString & UserName){
	//判断是否是保存的账户名 如果是则显示密码和BrokerID
	for (int i = 0; i < m_vAccountInfo.size(); i++){
		if (m_vAccountInfo[i].AccountID == UserName){
			editPassword->setText(m_vAccountInfo[i].Password);
			editBrokerId->setText(m_vAccountInfo[i].BrokerID);
			checkSaveFlag->setCheckState(Qt::Checked);
			return;
		}
	}
	editPassword->setText("");
	editBrokerId->setText("");
	checkSaveFlag->setCheckState(Qt::Unchecked);
}

void CLoginDlg::ReadIniFile(){
	QString DefaultAccountID = "";
    //从配置文件Server.ini中读取Server信息
    QString IniFilePath="Server.ini";
    m_ServerSettings = new QSettings(IniFilePath,QSettings::IniFormat);
    m_ServerSettings->setIniCodec("UTF8");
    g_pMainwindow->m_ServerInfo.ServerName = m_ServerSettings->value("ServerInfo/ServerName","").toString();
    g_pMainwindow->m_ServerInfo.ServerTradeAddr = m_ServerSettings->value("ServerInfo/ServerTradeAddr","").toString();
    g_pMainwindow->m_ServerInfo.ServerMarketAddr = m_ServerSettings->value("ServerInfo/ServerMarketAddr","").toString();
    cmbServerList->addItem(g_pMainwindow->m_ServerInfo.ServerName);

    //从配置文件Account.ini读取Account信息
    IniFilePath="Account.ini";
    m_AccountSettings = new QSettings(IniFilePath,QSettings::IniFormat);
    QString AccountID = "AccountInfo/AccountID";
    for(int iLoop = 1; iLoop < 4; iLoop++){//默认保存三个账户的登录信息
        QString key = AccountID + QString::number(iLoop,10);
        QString value=m_AccountSettings->value(key,"").toString();
        if(value != ""){
            AccountItem *accountItem = new AccountItem();
            accountItem->setAccountNumber(value);
            QObject::connect(accountItem, SIGNAL(showAccount(QString)), this, SLOT(showAccount(QString)));
            QObject::connect(accountItem, SIGNAL(removeAccount(QString)), this, SLOT(removeAccount(QString)));
            QListWidgetItem *list_item = new QListWidgetItem(listWidget);
            listWidget->setItemWidget(list_item, accountItem);
            m_vAccountHis.push_back(value);
        }
		if (iLoop == 1){
			cmbUsername->setCurrentText(value);//默认获取第一个账户作为默认账户
			DefaultAccountID= value;
		}
    }
	//读取默认账户的信息
	int SaveCnt=m_AccountSettings->value("SaveInfo/SaveCnt","0").toInt();
	if (SaveCnt != 0){
		QString AccountIDKey="SaveInfo/AccountID";
		QString	PasswordKey="SaveInfo/Password";
		QString	BrokerIDKey="SaveInfo/BrokerID";
		for (int i = 0; i < SaveCnt ; i++){
			AccountInfo accountTemp;
			QString AccountID=m_AccountSettings->value(AccountIDKey + QString::number(i+1),"").toString();
			QString	Password=m_AccountSettings->value(PasswordKey + QString::number(i+1),"").toString();
			QString	BrokerID=m_AccountSettings->value(BrokerIDKey + QString::number(i+1),"").toString();
			accountTemp.AccountID = AccountID;
			accountTemp.Password  = Password;
            accountTemp.BrokerID  = BrokerID;
			m_vAccountInfo.push_back(accountTemp);

			if (DefaultAccountID == AccountID){
				cmbUsername->setCurrentText(DefaultAccountID);
				editPassword->setText(Password);
				editBrokerId->setText(BrokerID);
				checkSaveFlag->setCheckState(Qt::Checked);
			}
		}		
    }
}

void CLoginDlg::userLogin(){
    int nSaveFlag = checkSaveFlag->checkState();
    m_szUsername = cmbUsername->currentText();
    m_szPassword = editPassword->text();
    m_szBrokerId = editBrokerId->text();

    if("" == m_szUsername || "" == m_szPassword){
        QMessageBox::critical(this, QString("ERROR"), QString("请输入有效账户及密码"));
    }else{
		//通讯服务器的反馈标志
		//m_bResponsed = false;
		//m_ResponsedType = ERRORMSG;
		//CTP服务器的反馈标志
		m_bCTPResponsed = false;
        m_iErrorID   = 1;

        //登录通讯服务器    第三个参数为UserType 1代表为投资顾问
		//char cUserName[100],cPassword[100];
		//strcpy(cUserName,m_szUsername.toStdString().c_str());
		//strcpy(cPassword,m_szPassword.toStdString().c_str());
        //g_pMainwindow->m_pFundLib->DoLogin(cUserName,cPassword,1);

		//循环等待通讯服务器反馈的登录响应
		int iTimeCnt = 0;
		//while (!m_bResponsed){
			//Sleep(500);
			//if (++iTimeCnt == 10){//超过一定时间后显示用户登录超时
				//QMessageBox::critical(NULL, QString("ERROR"), QString("用户登录通讯服务器超时!"));
				//return;
			//}
		//}

        //if (m_ResponsedType != ERRORMSG ){
			//默认获取第一个资金帐户进行登录
			//QString userName = QString(g_pMainwindow->m_vAccounts[0].szAccountID);
			//QString password = QString(g_pMainwindow->m_vAccounts[0].szPassword);
            QString ServerName = cmbServerList->currentText();

			//Modify 2015-11-11
            g_pMainwindow->InitTradeObject(m_szUsername,m_szPassword,m_szBrokerId,ServerName);//初始化交易服务器
			g_pMainwindow->InitMdObject(m_szUsername,m_szPassword,m_szBrokerId);//初始化行情服务器
            emit SigShowStatusText(QStringLiteral("登录进度:初始化交易服务器…"));

			//循环等待CTP服务器反馈的登录响应
			iTimeCnt = 0;
            while (!m_bCTPResponsed){
                //等待50毫秒
                QTime t;
                t.start();
                while(t.elapsed()<60)
                    QCoreApplication::processEvents();
                if (++iTimeCnt == 2000){//超过一定时间后显示用户登录超时
                    //QMessageBox::critical(this, QString("ERROR"), QStringLiteral("用户登录CTP服务器超时"));
                    emit SigShowStatusText(QStringLiteral("用户登录CTP服务器超时"));
                    //g_pMainwindow->RegisterSpi();
					return;
				}
			}

            if (0 == m_iErrorID ){//用户登录成功
                //保存帐号登录历史
                QString AccountIDKey="AccountInfo/AccountID";
                int index = 1;
                m_AccountSettings->setValue(AccountIDKey + QString::number(index++),m_szUsername);
                for (int i = 0; i < m_vAccountHis.size(); i++){
                    if( m_vAccountHis[i] != m_szUsername  && index <4){
                        m_AccountSettings->setValue(AccountIDKey + QString::number(index++),m_vAccountHis[i]);
                    }
                }
                //保存账户密码信息
				if (nSaveFlag == Qt::Checked){
					//检查是否已经保存该账户的信息
                    int iFlg = false;
					for (int i = 0; i < m_vAccountInfo.size(); i++){
                        if (m_vAccountInfo[i].AccountID == m_szUsername){
                            iFlg = true;//已保存
                            break;
						}
                    }
                    if(iFlg == false){//未保存
                        AccountInfo AccountTemp;
                        AccountTemp.AccountID = m_szUsername ;
                        AccountTemp.Password  = m_szPassword ;
                        AccountTemp.BrokerID  = m_szBrokerId ;
                        m_vAccountInfo.push_back(AccountTemp);
                    }
				}else if (nSaveFlag == Qt::Unchecked){
                    //未保存账户信息 判断之前是否保存 如果保存则进行删除
                    for (vector<AccountInfo>::iterator it = m_vAccountInfo.begin(); it != m_vAccountInfo.end(); it++){
                        if (it->AccountID == m_szUsername){//之前保存
                            m_vAccountInfo.erase(it);
                            break;
                        }
                    }
				}
                SaveAccountInfo();
				this->accept();
			}else{
                QMessageBox::critical(this, QString("ERROR"), QString(m_strCTPErrorMsg));
			}
		//}else{
			//QMessageBox::critical(NULL, QString("ERROR"), QString(m_strErrorMsg));
		//}
    }
}
void CLoginDlg::SaveAccountInfo(){
    //清除保存的账户密码信息 登录成功后重新写入
    m_AccountSettings->remove("SaveInfo/");
	//将保存的账户信息写入配置文件中
	m_AccountSettings->setValue("SaveInfo/SaveCnt",m_vAccountInfo.size());
	QString AccountIDKey="SaveInfo/AccountID";
	QString	PasswordKey="SaveInfo/Password";
	QString	BrokerIDKey="SaveInfo/BrokerID";
	for (int i = 0; i < m_vAccountInfo.size(); i++){
		m_AccountSettings->setValue(AccountIDKey + QString::number(i+1),m_vAccountInfo[i].AccountID);
		m_AccountSettings->setValue(PasswordKey + QString::number(i+1),m_vAccountInfo[i].Password);
		m_AccountSettings->setValue(BrokerIDKey + QString::number(i+1),m_vAccountInfo[i].BrokerID);
	}
}
//CTP服务器登陆成功后返回信息 调用函数
void CLoginDlg::OnRspUserLogin(CThostFtdcRspInfoField *pRspInfo){
    if(0 != pRspInfo->ErrorID){
        m_bCTPResponsed = true;
        m_iErrorID   = pRspInfo->ErrorID;
		m_strCTPErrorMsg = tr("用户登录失败!")+tr("\n错误代码=") + QString::number(pRspInfo->ErrorID) + tr("\n错误信息=") +  QString::fromLocal8Bit(pRspInfo->ErrorMsg);
    }else{
        emit SigShowStatusText(QStringLiteral("登录进度:登录成功,查询合约…"));
    }
}
//查询合约信息完毕后调用函数
void CLoginDlg::OnRspQryInstrument(){
    m_bCTPResponsed = true;
    m_iErrorID = 0;
    emit SigShowStatusText(QStringLiteral("登录进度:查询合约列表完毕"));
}
//通讯服务器登录成功后 返回信息 调用函数
void CLoginDlg::OnRspUserLogin(int iType,QString strMsg){

    //m_ResponsedType = iType;
    //if(ERRORMSG == m_ResponsedType){
        //m_strErrorMsg = tr("用户登录失败!")+ tr("\n错误信息=") +  strMsg;
    //}
    //m_bResponsed = true;
}
void CLoginDlg::cancelLogin()
{
    g_pMainwindow->close();
    delete g_pMainwindow;
	this->close();
}

void CLoginDlg::showAccount(QString sText){
	cmbUsername->setCurrentText(sText);
	cmbUsername->hidePopup();

	for (int i = 0; i < m_vAccountInfo.size(); i++){
		if (m_vAccountInfo[i].AccountID == sText){
			editPassword->setText(m_vAccountInfo[i].Password);
			editBrokerId->setText(m_vAccountInfo[i].BrokerID);
			checkSaveFlag->setCheckState(Qt::Checked);
			return;
		}
	}
	editPassword->setText("");
	editBrokerId->setText("");
	checkSaveFlag->setCheckState(Qt::Unchecked);
}
void CLoginDlg::removeAccount(QString sText){
    int iRow = listWidget->currentRow();
    listWidget->takeItem(iRow);
    cmbUsername->hidePopup();
}

void CLoginDlg::displayUser(QString account)
{
	cmbUsername->setEditText(account);
	cmbUsername->hidePopup();
}
void CLoginDlg::removeUser(QString account)
{
	msgBox->setInfo(tr("remove account"), tr("are you sure to remove account?"), QPixmap(":/loginDialog/attention"), false);
	if(msgBox->exec() == QDialog::Accepted)
	{
		int listCount = listWidget->count();
		for(int i=0; i<listCount; i++)
		{
			QListWidgetItem *item = listWidget->item(i);
			AccountItem *accountItem = (AccountItem *)(listWidget->itemWidget(item));
			QString accountNumber = accountItem->getAccountNumber();
			if(account == accountNumber)
			{
				listWidget->takeItem(i);
				delete item;

				break;
			}
		}
	}
	cmbUsername->hidePopup();
}
